<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChWordGroupMapper;
use App\CustHub\Model\ChWord;
use App\CustHub\Model\ChWordGroup;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;

class WordGroupService extends AbstractService
{
    public $mapper;

    public function __construct(ChWordGroupMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function save(array $data): mixed
    {
        $data['sort'] = $this->mapper->model::query() -> max('sort') + 1;
        return $this->mapper->save($data);
    }


    #[Transaction]
    public function delGroup(array $params): bool
    {
        $id = $params['id'];
        ChWordGroup::query() -> where('id',$id) -> delete();
        $ids = ChWordGroup::query() -> where('p_id',$id) -> pluck('id');
        $ids = !empty($ids)?$ids:[];
        $ids[] = $id;
        ChWordGroup::query() -> where('p_id',$id) -> delete();
        ChWord::query() -> whereIn('group_id',$ids) -> update(['group_id'=>0]);
        return true;
    }
}